package com.example.myapplication.Fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.ListView
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.android.volley.DefaultRetryPolicy
import com.android.volley.Request
import com.android.volley.toolbox.HurlStack
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.example.myapplication.Model.Forecast
import com.example.myapplication.Model.Weather
import com.example.myapplication.R
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.security.KeyStore
import javax.net.ssl.*

class WeatherFragment : Fragment() {

    private lateinit var imageView: ImageView
    private lateinit var textViewCity: TextView
    private lateinit var textViewProvince: TextView
    private lateinit var textViewWendu: TextView
    private lateinit var textViewShidu: TextView
    private lateinit var listView: ListView

    private var cityCode: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            cityCode = it.getString("city_code")
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_weather, container, false)

        imageView = view.findViewById(R.id.imageView)
        textViewCity = view.findViewById(R.id.textView_city)
        textViewProvince = view.findViewById(R.id.textView_province)
        textViewWendu = view.findViewById(R.id.textView_wendu)
        textViewShidu = view.findViewById(R.id.textView_shidu)
        listView = view.findViewById(R.id.listView)

        cityCode?.let { fetchWeatherData(it) }

        return view
    }

    private fun fetchWeatherData(cityCode: String) {
        val queue = Volley.newRequestQueue(requireContext(), createHurlStackWithTls12())
        val url = "http://t.weather.itboy.net/api/weather/city/$cityCode"

        val stringRequest = StringRequest(
            Request.Method.GET, url,
            { response ->
                val gson = Gson()
                val weatherType = object : TypeToken<Weather>() {}.type
                try {
                    val weather = gson.fromJson<Weather>(response, weatherType)
                    textViewCity.text = weather.cityInfo.city
                    textViewProvince.text = weather.cityInfo.parent
                    textViewShidu.text = weather.data.shidu
                    textViewWendu.text = weather.data.wendu

                    val firstDay = weather.data.forecast.firstOrNull()
                    firstDay?.let {
                        when (it.type) {
                            "晴" -> imageView.setImageResource(R.drawable.sun)
                            "阴" -> imageView.setImageResource(R.drawable.cloud)
                            "多云" -> imageView.setImageResource(R.drawable.mcloud)
                            "阵雨" -> imageView.setImageResource(R.drawable.rain)
                            "打雷" -> imageView.setImageResource(R.drawable.thunder)
                        }
                    }

                    val forecastAdapter = ArrayAdapter<Forecast>(requireContext(), android.R.layout.simple_list_item_1, weather.data.forecast)
                    listView.adapter = forecastAdapter
                } catch (e: Exception) {
                    Log.e("Weather", "Failed to parse JSON: ${e.message}", e)
                    textViewCity.text = "Error: Failed to parse JSON"
                }
            },
            { error ->
                Log.e("Weather", "Network request failed: ${error.message}", error)
                textViewCity.text = "Error: Network request failed"
            }
        ).apply {
            // 设置超时时间为 10 秒
            setShouldCache(false)
            setRetryPolicy(
                DefaultRetryPolicy(
                10000,  // 超时时间（毫秒）
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,  // 重试次数
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT  // 重试间隔倍数
            )
            )
        }

        queue.add(stringRequest)
    }

    private fun createSslSocketFactory(): SSLSocketFactory? {
        try {
            val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
            trustManagerFactory.init(null as KeyStore?)

            val sslContext = SSLContext.getInstance("TLSv1.2")
            sslContext.init(null, trustManagerFactory.trustManagers, null)

            return sslContext.socketFactory
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    private fun createHurlStackWithTls12(): HurlStack {
        val sslSocketFactory = createSslSocketFactory()
        return object : HurlStack() {
            @Throws(IOException::class)
            override fun createConnection(url: URL?): HttpURLConnection {
                val connection = super.createConnection(url)
                if (url?.protocol == "https" && sslSocketFactory != null) {
                    (connection as HttpsURLConnection).sslSocketFactory = sslSocketFactory
                }
                return connection
            }
        }
    }
}